'use client'

import { AnimatePresence } from 'framer-motion'
import dynamic from 'next/dynamic'
import { SignedIn, SignedOut, useAuth } from '@clerk/nextjs'
import TriggerComponent from './TriggerComponent'
import useIsLogged from '@/hooks/common/use-loggin'
import { useEffect } from 'react'
import { useCreateUser } from '@/hooks/auth/use-create-user'
import { RootContext } from '@/app/RootContext'
import UserMenu from '@/components/UserMenu'
import { Avatar, NavbarItem } from '@nextui-org/react'
import NextIcon from '../NextIcon'

const UserAuthFromIcon = dynamic(() => import('./UserAuthFromIcon'))

export default function UserAuth() {
  const { userInfo } = RootContext.useContainer()
  const { createUser } = useCreateUser()

  const isLogged = useIsLogged()

  const auth = useAuth()

  useEffect(() => {
    if (isLogged) {
      // createUser()
    } else {
      localStorage.removeItem('isUserUpdate')
    }
  }, [isLogged, auth])

  const AvatarUser = (
    <div className="relative">
      <Avatar
        showFallback
        icon={<NextIcon type="user1" size={30} />}
        className="cursor-pointer dark:filter-none"
        src={userInfo?.imageUrl}
        fallback={<NextIcon type="user1" size={30} />}
      />

      <UserAuthFromIcon className="absolute bottom-[-4px] right-[-5px]" />
    </div>
  )

  return (
    <AnimatePresence>
      <SignedIn key="user-info">
        <div className="pointer-events-auto flex h-11 items-center justify-end">
          <UserMenu>{AvatarUser}</UserMenu>
        </div>
      </SignedIn>

      <SignedOut key="sign-in">
        <div className="pointer-events-auto flex h-11 items-center justify-end">
          <TriggerComponent />
        </div>
      </SignedOut>
    </AnimatePresence>
  )
}
